# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools, _
from odoo.exceptions import ValidationError, Warning

import sys
import os
from os import path
d = path.dirname(__file__)
parent_path = os.path.dirname(os.path.dirname(d))
sys.path.append(parent_path)
from celery_odoo import sms

from parameter import SALVAGER_ROLES
import time
import datetime
import pytz
import json
from lxml import etree
import logging

_logger = logging.getLogger(__name__)

# 消息模板
# 被困人员接收的短信 175712
MESSAGE_CALL_PERSON_TEMPLATE = u"您好，救援人员会尽快赶到现场!救援人员号码：{0}，电梯不是封闭空间，不会有窒息的危险"
# 发给救援人员的短信
MESSAGE_SAVALGER_TEMPLATE = u"您好，报警人:{0} ,报警电话:{1} ,备注:{2} ,电梯编码:{3},电梯名称:{4} ,使用单位:{5}，救援完成后请及时给{6}反馈"
# 发给区县局人员的短信
MESSAGE_QS_TEMPLATE = u"您好，{0}电梯，在{1}，接收到来自报警人：{2}的报警，内容如下：{3}，请予以关注。"

CONSULT_SOLVED_STATE = [
    ('yes', '已解决'),
    ('no', '未解决'),
]

WORK_ORDER_STATE = [
    ('draft', '尚未接警'),
    ('center_received', u'中心接警'),
    ('command_and_dispatch', u'指挥调度'),
    ('keep_track_rescure', u'救援跟踪'),
    ('archive', u'完成归档'),
]

RESPONSE_LEVELS = [
    ('1', '一级响应'),
    ('2', '二级响应'),
    ('3', '三级响应'),
]

SAVE_STATES = [
    ('ready', '准备中'),
    ('has_departed', '已出发'),
    ('has_arrived', '到达现场'),
    ('saving', '救援中'),
    # 要通过手机靠一靠
    ('finished', '救援完成'),
    ('cant_arrive', '无法到达，重新调度')
]

SAVE_RESULT = [('save_sucess', '救援成功'), ('save_failure', '救援失败'),
               ('get_out_yourself', '自行脱困'), ('misinformation', '误报')]


class WorkOrderConsult(models.Model):
    """
    咨询
    """
    _name = "tyibs.er.work.order.consult"
    _order = "id desc"

    name = fields.Char(string=u"咨询人员", size=50, required=True)
    phone = fields.Char(string=u"咨询电话", size=100, required=True)
    service_time = fields.Datetime(string=u"咨询时间", default=fields.Datetime.now)
    has_solved = fields.Selection(CONSULT_SOLVED_STATE, string=u"是否解决")
    service_id = fields.Many2one(
        "tyibs.base.lift.dispose.center.customer.service",
        string=u"客服人员",
        required=True)
    user_id = fields.Many2one(
        related="service_id.res_user_id", store=True, string=u"所属用户")
    question = fields.Text(string=u"问题描述")
    feedback = fields.Text(string=u"反馈意见")
    remark = fields.Text(string=u"备注")


class WorkOrderBase(models.BaseModel):
    _name = "tyibs.er.work.order.base"
    _order = "id desc"

    # 5.8号追加新字段
    alarms_order_num = fields.Char(string=u'接警单号', default=lambda self: self.env["ir.sequence"].next_by_code(self._name + ".sequence"))
    alarms_person_name = fields.Char(string=u'接警人姓名')
    alarms_type = fields.Char(string=u'接警类型')
    lift_code = fields.Char(related="lift_id.code", store=True)
    # zr 为APP增加字段
    lift_register_code = fields.Char(related="lift_id.register_code")
    lift_rfid = fields.Char(related="lift_id.rfid_code", store=True)
    # 基本情况
    name = fields.Char(string=u"报警人员", size=50, required=True)
    phone = fields.Char(string=u"报警电话", size=100, required=True)

    lift_id = fields.Many2one("tyibs.base.lift", string=u"电梯", required=True)
    lift_address = fields.Char(related="lift_id.use_address", store=True)
    lift_use_company_id = fields.Many2one(
        related="lift_id.use_company_id", store=True)
    lift_use_company_contact = fields.Char(
        related="lift_use_company_id.linkman", store=True)
    lift_use_company_contact_phone = fields.Char(
        related="lift_use_company_id.linkman_tel", store=True)
    lift_maintenance_company_id = fields.Many2one(
        related="lift_id.maintenance_company_id", store=True)
    lift_maintenance_company_contact = fields.Char(
        related="lift_maintenance_company_id.contact", store=True)
    lift_maintenance_company_contact_phone = fields.Char(
        related="lift_maintenance_company_id.mobile", store=True)

    service_time = fields.Datetime(string=u"投诉时间", default=fields.Datetime.now)
    service_id = fields.Many2one(
        "tyibs.base.lift.dispose.center.customer.service",
        string=u"客服人员",
        required=True)
    user_id = fields.Many2one(
        related="service_id.res_user_id", store=True, string=u"所属用户")

    # 可能的响应单位
    response_use_company_id = fields.Many2one(
        "tyibs.base.lift.use.company", string=u"使用单位")
    response_maintenance_company_id = fields.Many2one(
        "tyibs.base.maintenance.company", string=u"维保单位")
    response_qs_company_id = fields.Many2one(
        "tyibs.base.qs.company", string=u"监察单位")

    # 响应情况
    response_type = fields.Selection(
        [('maintenance', '维保公司'), ('use', '使用单位'), ('qs', '监管部门')],
        string=u"响应类型")
    response_company_name = fields.Char(string=u"响应单位名称")
    response_person_name = fields.Char(string=u"响应负责人")
    response_person_mobile = fields.Char(string=u"响应负责人电话")
    response_time = fields.Datetime(string=u"响应时间")

    # 处理情况
    do_person_name = fields.Char(string=u"处理人员")
    do_person_mobile = fields.Char(string=u"处理人员电话")
    estimated_arrival_time = fields.Datetime(string=u'预计到达时间')
    do_arrived_time = fields.Datetime(string=u"处理人员到达时间")
    do_finish_time = fields.Datetime(string=u"处理完成时间")

    archive_time = fields.Datetime(string=u"归档时间")
    # 维修结果
    do_result = fields.Selection(
        [('ok', '完成'), ('no', '未完成')], string=u"处理结果", default='no')
    # 接警单大状态
    state = fields.Selection(
        WORK_ORDER_STATE, string=u"状态", default="center_received")
    remark = fields.Text(string=u"备注")

    comment_ids = fields.One2many(
        "tyibs.er.work.order.comment", compute="_get_comments", string=u"跟踪记录")

    @api.one
    def _get_comments(self):
        self.comment_ids = self.env['tyibs.er.work.order.comment'].search(
            [('res_model', '=', self._name), ('res_id', '=', self.id)])

    @api.model
    def create(self, values):
        record = super(WorkOrderBase, self).create(values)
        # 生成电梯生命周期事件
        lift_comment_vals = {
            "lift_id": record.lift_id.id,
            "category_id": self.env.ref("lift_base.tyibs_base_lift_comment_category_" + record._name.split('.')[-1]).id,
            "content": record.content,
            "operator_time": record.service_time,
            "res_model": record._name,
            "res_id": record.id
        }
        self.env["tyibs.base.lift.comment"].create(lift_comment_vals)
        return record

    @api.multi
    def center_received(self):
        for record in self:
            self.write({
                'state': 'center_received',
            })
        return True

    @api.multi
    def command_and_dispatch(self):
        return self.write({'state': 'command_and_dispatch'})

    @api.multi
    def keep_track_rescure(self):
        return self.write({'state': 'keep_track_rescure'})

    @api.multi
    def archive(self):
        return self.write({'state': 'archive'})

    @api.model
    def worker_order_query(self, service_id):
        """
        根据service_id查询坐席人员的工单，包括救援、投诉、报修
        :param service_id: 坐席人员id
        :return:
        """
        sql_item = "select alarms_order_num,alarms_person_name,alarms_type,state,lift_code,lift_address,phone,name,id,lift_id,service_id from %s where state != 'archive'"
        if service_id:
            sql_item += " and service_id = %s" % service_id
        sql_list = [
            sql_item % "tyibs_er_work_order_save",
            sql_item % "tyibs_er_work_order_repair",
            sql_item % "tyibs_er_work_order_compliant",
        ]
        sql = " union ".join(sql_list)
        self.env.cr.execute(sql)
        work_order = self.env.cr.dictfetchall()
        return work_order

    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        if context.get("search_from", False) == "qs_area":
            # args.append(('lift_id.qs_company_id', '=',
            #              self.env.user.qs_company_id.id))
            args.append(('lift_id.area_id', '=',
                         self.env.user.qs_company_id.area_id.id))

        return super(WorkOrderBase, self).search(args, offset, limit, order,
                                                 count)

    @api.model
    def fields_view_get(self,
                        view_id=None,
                        view_type='form',
                        toolbar=False,
                        submenu=False):
        context = self._context or {}
        res = super(WorkOrderBase, self).fields_view_get(
            view_id=view_id,
            view_type=view_type,
            toolbar=toolbar,
            submenu=False)
        if context.get("readonly", False) == 1:
            if res['type'] == "form" or res['type'] == 'tree':
                doc = etree.XML(res['arch'])
                doc.xpath("//{}".format(res['type']))[0].set("edit", "false")
                res['arch'] = etree.tostring(doc)
        return res

    @api.model
    def fix_response(self, user_company_id, main_company_id):
        """
        报修响应
        :param user_company_id: 使用单位ID
        :param mt_company_id: 维保单位ID
        :return: 报修响应单位信息 list
        """
        er_call_config_domain = [('config_type', '=', 'repair'), ('unit_type', 'in', ['use', 'maintenance'])]
        return self.response_info(user_company_id, main_company_id, er_call_config_domain)

    @api.model
    def complaint_response(self, user_company_id, main_company_id):
        """
        投诉响应
        :param user_company_id: 使用单位ID
        :param main_company_id: 维保单位ID
        :return: 投诉响应单位信息 list
        """
        er_call_config_domain = [('config_type', '=', 'repair'), ('unit_type', 'in', ['use', 'maintenance'])]
        return self.response_info(user_company_id, main_company_id, er_call_config_domain)

    def response_info(self, user_company_id, main_company_id, er_call_config_domain):
        dict_roles = dict(SALVAGER_ROLES)
        er_config_ids = self.env['tyibs.er.call.config'].search(er_call_config_domain)
        result_list = []
        use_company_list = []
        maintenance_company_list = []
        for config_item in er_config_ids:
            if config_item.unit_type == "use":
                # 使用单位救援人员
                use_company_salvager_domain = [('enterprise_id', '=', user_company_id), ('role', '=', config_item.role)]
                use_company_salvager_ids = self.env['tyibs.base.lift.use.company.salvager'].search(
                    use_company_salvager_domain)
                for item in use_company_salvager_ids:
                    use_company_list.append({
                        "company_id": user_company_id,
                        "company_name": item.enterprise_id.name,
                        "company_type": u'使用单位',
                        "level": dict_roles[item.role],
                        "link_man": item.name,
                        "link_man_phone": item.mobile,
                        "message": u'短信'
                    })
            elif config_item.unit_type == "maintenance":
                # 维保单位救援人员
                maintenance_company_salvager_domain = [('enterprise_id', '=', main_company_id),
                                                       ('role', '=', config_item.role)]
                maintenance_company_salvager_ids = self.env['tyibs.base.maintenance.company.salvager'].search(
                    maintenance_company_salvager_domain)
                for item in maintenance_company_salvager_ids:
                    maintenance_company_list.append({
                        "company_id": main_company_id,
                        "company_name": item.enterprise_id.name,
                        "company_type": u'维保单位',
                        "level": dict_roles[item.role],
                        "link_man": item.name,
                        "link_man_phone": item.mobile,
                        "message": u'短信'
                    })
        result_list.extend(maintenance_company_list)
        result_list.extend(use_company_list)
        return result_list

    def cancel_order(self, kw):
        """
        取消接警
        :param kw:
        :return:
        """
        result = {'code': 0, 'message': 'success'}
        try:
            self.write({
                'state': 'archive',
                'save_result': kw.get("save_result", "misinformation"),
                'remark': kw.get("remark", u"误报"),
                'archive_time': datetime.datetime.now(),
                'do_result': 'ok'
            })
            self.env["tyibs.er.work.order.comment"].create({
                'stage': 'archive',
                'content': u"取消报警",
                'res_model': self._name,
                'res_id': self.id
            })
        except Exception, e:
            result['code'] = 1
            result['message'] = e.message
        return result


class WorkOrderSave(models.Model):
    _inherit = "tyibs.er.work.order.base"
    _name = "tyibs.er.work.order.save"

    # 中心接警填写，也即是模型里面的跟踪备注
    content = fields.Text(string="报警内容")
    """
    救援记录
    """

    save_company_id = fields.Many2one(
        "tyibs.base.maintenance.company", string=u"维保公司")
    save_employee_id = fields.Many2one(
        "tyibs.base.maintenance.company.employee",
        string=u"维保人员",
        domain="[('enterprise_id','=',save_company_id)]")

    # TODO: 应该和接收任务的维保人员关联 也就是APP上操作的
    save_employee_user_id = fields.Many2one("res.users", string=u"关联的用户")
    response_level = fields.Selection(RESPONSE_LEVELS, string=u"响应级别")
    # 救援人员在手机接收任务的时间
    save_accept_time = fields.Datetime(string=u"接收任务时间")
    # 是否有伤亡
    is_Trap = fields.Boolean(string=u'是否有伤亡')
    # 被困人数
    trapped_people_count = fields.Char(string=u'被困人数')

    # 到达现场的情况
    car_id = fields.Many2one("tyibs.base.maintenance.rescue.vehicle", string=u"救援车辆")
    arrived_ln = fields.Float(string=u"到达地点经度", digits=(32, 6))
    arrived_la = fields.Float(string=u"到达地点纬度", digits=(32, 6))
    arrived_image = fields.Binary(
        string=u"到达地点照片", attachment=True, public=True)

    arrived_duration = fields.Integer(string=u"到达时长(分)", compute="compute_arrived_duration", store=True)

    save_finished_time = fields.Datetime(string=u"救援完成时间")
    save_state = fields.Selection(SAVE_STATES, string=u"救援状态")
    save_result = fields.Selection(SAVE_RESULT, string=u'救援结果')
    save_duration = fields.Char(string=u"救援时长", compute="compute_save_duration", store=True)

    # 归档时候填写
    fault_category_id = fields.Many2one(
        "tyibs.base.fault.category", string=u"故障类别")
    fault_item_id = fields.Many2one(
        "tyibs.base.fault.item",
        string=u"故障明细",
        domain="[('category_id','=',fault_category_id)]")
    fault_description = fields.Text(string=u"故障描述")


    @api.model
    def create(self, vals):

        record = super(WorkOrderSave, self).create(vals)
        # 救援工单创建时向：区县局-股长发送一条短信
        # u"您好，{0}电梯，在{1}，接收到来自报警人：{2}的报警，内容如下：{3}，请予以关注。"
        content = u"使用单位：" + (record.lift_use_company_id.name or u"未知") + u"。地址：" + (record.lift_address or u"未知") + u"。报警内容：" + (record.content or u"未知")
        message_content = MESSAGE_QS_TEMPLATE.format(record.lift_code,
                                                     datetime.datetime.now(pytz.timezone('Asia/Shanghai')).strftime("%Y-%m-%d %H:%M:%S"),
                                                     record.name, content)
        qs_company_id = self.env["tyibs.base.qs.company"].search([('level','=','2'),('area_id','=',record.lift_id.area_id.id)],limit=1)
        unit_chief = self.env["tyibs.base.qs.company.employee"].search([("enterprise_id", "=", qs_company_id.id), ("position", "=", "unit_chief"), ("has_dimission", "=", False)], limit=1)
        mobile = '18552004028'
        if unit_chief:
            mobile = unit_chief.mobile.lstrip('0')
        _logger.info(u"发送给区县局股长：%s" % mobile)
        _logger.info(u"发送内容：%s" % message_content)
        run_env = self.env['ir.config_parameter'].get_param('tyibs.runtime.environment')
        if run_env == "master":
            sms.send_message.delay(mobile, message_content)
            _logger.info(u"给区县局的短信已发送。")
        unit_chief_name = unit_chief.name or u"未知"
        comment_vals = {
            "res_model": "tyibs.er.work.order.save",
            "res_id": record.id,
            "arlams_order_num": record.alarms_order_num,
            "operation_category_id": self.env.ref("er.tyibs_er_work_order_operation_2").id,
            "contact": unit_chief_name,
            "phone": mobile,
            "stage": record.state,
            "do_time": datetime.datetime.now(),
            "content": u"发送给：" + unit_chief_name + "-" + mobile + u"\n发送内容：" + message_content
        }
        self.env["tyibs.er.work.order.comment"].create(comment_vals)
        return record

    @api.multi
    def write(self, vals):
        current_state = self.state
        result = super(WorkOrderSave, self).write(vals)
        if current_state == "center_received" and vals.get("state", False) == "command_and_dispatch":
            # 调度完成后给救援人员(处理人员)和被困人员发送短信
            self.response_send_message()
        return result

    def response_send_message(self):
        """
        救援人员响应时(在手机app上接单)发送短信
        :return: 无返回值
        """
        run_env = self.env['ir.config_parameter'].get_param('tyibs.runtime.environment')

        comment_vals = {
            "res_model": "tyibs.er.work.order.save",
            "res_id": self.id,
            "arlams_order_num": self.alarms_order_num,
            "operation_category_id": self.env.ref("er.tyibs_er_work_order_operation_2").id,
            "stage": self.state,
            "do_time": datetime.datetime.now(),
        }
        # 发给救援人员(处理人员)
        # 您好，报警人:{0} ,报警电话:{1} ,备注:{2} ,电梯编码:{3},电梯名称:{4} ,使用单位:{5}，救援完成后请及时给{6}反馈
        salvager_mobile = self.do_person_mobile.lstrip('0')
        trap_mobile = self.phone.lstrip('0')
        message_content = MESSAGE_SAVALGER_TEMPLATE.format(self.name, trap_mobile, self.content, self.lift_code,
                                                           self.lift_id.use_address, self.lift_use_company_id.name, '96333')
        _logger.info(u"发送给救援人员：%s" % salvager_mobile)
        _logger.info(u"发送内容：%s" % message_content)
        if run_env == "master":
            _logger.info(u"给救援人员的短信已发送。")
            sms.send_message.delay(salvager_mobile, message_content)
        comment_vals["content"] = u"发送给：" + self.do_person_name + "-" + salvager_mobile + u"\n发送内容：" + message_content
        comment_vals["contact"] = self.do_person_name
        comment_vals["phone"] = salvager_mobile
        self.env["tyibs.er.work.order.comment"].create(comment_vals)

        # 发送给被困人员
        # 您好，救援人员会尽快赶到现场!救援人员号码：{0}，电梯不是封闭空间，不会有窒息的危险
        _logger.info(u"发送给被困人员：%s" % trap_mobile)
        _logger.info(u"发送内容：%s" % MESSAGE_CALL_PERSON_TEMPLATE.format(salvager_mobile))
        if run_env == "master":
            sms.send_message.delay(trap_mobile, MESSAGE_CALL_PERSON_TEMPLATE.format(salvager_mobile))
            _logger.info(u"给被困人员的短信已发送。")
        comment_vals["content"] = u"发送给：" + self.name + "-" + trap_mobile + u"\n发送内容：" + MESSAGE_CALL_PERSON_TEMPLATE.format(salvager_mobile)
        comment_vals["contact"] = self.name
        comment_vals["phone"] = trap_mobile
        self.env["tyibs.er.work.order.comment"].create(comment_vals)

    @api.depends("service_time", "do_finish_time")
    def compute_save_duration(self):
        # 计算救援时长
        if self.do_finish_time and self.service_time and self.do_finish_time > self.service_time:
            service_time = datetime.datetime.strptime(self.service_time,
                                                      "%Y-%m-%d %H:%M:%S")
            do_finish_time = datetime.datetime.strptime(
                self.do_finish_time, "%Y-%m-%d %H:%M:%S")
            duration = str(do_finish_time - service_time).replace(" days,", u"天")
            self.save_duration = duration
        else:
            self.save_duration = ""

    @api.multi
    @api.depends("response_time", "do_arrived_time")
    def compute_arrived_duration(self):
        # 计算到达时长，响应时间->到达时间
        for item in self:
            if item.response_time and item.do_arrived_time and item.do_arrived_time > item.response_time:
                response_time = datetime.datetime.strptime(item.response_time,
                                                          "%Y-%m-%d %H:%M:%S")
                do_arrived_time = datetime.datetime.strptime(
                    item.do_arrived_time, "%Y-%m-%d %H:%M:%S")
                duration_total_minutes = (do_arrived_time - response_time).total_seconds() / 60
                if not duration_total_minutes.is_integer():
                    duration_total_minutes += 1
                item.arrived_duration = int(duration_total_minutes)
            else:
                item.arrived_duration = 0

    @api.model
    def first_response(self, user_company_id, main_company_id):
        """
        一级响应
        :param user_company_id: 使用单位ID
        :param main_company_id: 维保单位ID
        :return: 一级响应救援人员
        """
        # 条件：类型为救援、救援层级为一级，单位类型为使用单位和维保单位
        er_call_config_domain = [('config_type', '=', 'save'), ('response_level', '=', '1'), ('unit_type', 'in', ['use', 'maintenance'])]
        dict_roles = dict(SALVAGER_ROLES)
        result_list = []
        er_config_ids = self.env['tyibs.er.call.config'].search(er_call_config_domain)
        use_company_list = []
        maintenance_company_list = []
        for config_item in er_config_ids:
            if config_item.unit_type == "use":
                # 使用单位救援人员
                use_company_salvager_domain = [('enterprise_id', '=', user_company_id), ('role', '=', config_item.role)]
                use_company_salvager_ids = self.env['tyibs.base.lift.use.company.salvager'].search(use_company_salvager_domain)
                for item in use_company_salvager_ids:
                    use_company_list.append({
                        "company_id": user_company_id,
                        "company_name": item.enterprise_id.name,
                        "company_type": u'使用单位',
                        "level": dict_roles[item.role],
                        "link_man": item.name,
                        "link_man_phone": item.mobile,
                        "message": u'短信'
                    })
            elif config_item.unit_type == "maintenance":
                # 维保单位救援人员
                maintenance_company_salvager_domain = [('enterprise_id', '=', main_company_id), ('role', '=', config_item.role)]
                maintenance_company_salvager_ids = self.env['tyibs.base.maintenance.company.salvager'].search(maintenance_company_salvager_domain)
                for item in maintenance_company_salvager_ids:
                    maintenance_company_list.append({
                        "company_id": main_company_id,
                        "company_name": item.enterprise_id.name,
                        "company_type": u'维保单位',
                        "level": dict_roles[item.role],
                        "link_man": item.name,
                        "link_man_phone": item.mobile,
                        "message": u'短信'
                })
        result_list.extend(maintenance_company_list)
        result_list.extend(use_company_list)
        return result_list

    @api.model
    def first_response_by_lift_code(self, lift_code):
        """
        一级响应
        :param lift_code: 电梯编号
        :return: 一级响应救援人员
        """
        # 条件：类型为救援、救援层级为一级，单位类型为使用单位和维保单位
        er_call_config_domain = [('config_type', '=', 'save'), ('response_level', '=', '1'),
                                 ('unit_type', 'in', ['use', 'maintenance'])]
        dict_roles = dict(SALVAGER_ROLES)
        lift_id = self.env["tyibs.base.lift"].search([('code', '=', lift_code)],limit=1)

        if not lift_id:
            return []

        site_ids = lift_id.maintenance_company_id.site_ids.filtered(lambda item: item.area_id == lift_id.area_id)

        er_config_ids = self.env['tyibs.er.call.config'].search(er_call_config_domain)
        use_company_list = []
        maintenance_company_list = []

        use_roles = []
        main_roles = []
        for item in er_config_ids:
            if item.unit_type == "use":
                use_roles.append(item.role)
            elif item.unit_type == "maintenance":
                main_roles.append(item.role)

        use_company_salvager_domain = [('enterprise_id', '=', lift_id.use_company_id.id),
                                       ('role', 'in', use_roles)]
        use_company_salvager_ids = self.env['tyibs.base.lift.use.company.salvager'].search(
            use_company_salvager_domain)
        for item in use_company_salvager_ids:
            use_company_list.append({
                "company_id": lift_id.use_company_id.id,
                "company_name": item.enterprise_id.name,
                "company_type": u'使用单位',
                "level": dict_roles[item.role],
                "link_man": item.name,
                "link_man_phone": item.mobile,
                "message": u'短信'
            })

        # 维保单位救援人员
        if site_ids:
            # 有救援站点
            maintenance_company_salvager_domain = ['|', '&', ('site_id', 'in', site_ids.ids),
                                                   ('role', 'in', main_roles), '&', ('role','=','head_of_unit'), ('enterprise_id','=',lift_id.maintenance_company_id.id)]
        else:
            maintenance_company_salvager_domain = [('enterprise_id', '=', lift_id.maintenance_company_id.id),
                                                   ('role', 'in', main_roles)]
        maintenance_company_salvager_ids = self.env['tyibs.base.maintenance.company.salvager'].search(
            maintenance_company_salvager_domain)
        for item in maintenance_company_salvager_ids:
            maintenance_company_list.append({
                "company_id": lift_id.maintenance_company_id.id,
                "company_name": item.enterprise_id.name,
                "company_type": u'维保单位',
                "level": dict_roles[item.role],
                "link_man": item.name,
                "link_man_phone": item.mobile,
                "message": u'短信'
            })




        # for config_item in er_config_ids:
        #     if config_item.unit_type == "use":
        #         # 使用单位救援人员
        #         use_company_salvager_domain = [('enterprise_id', '=', lift_id.use_company_id.id), ('role', '=', config_item.role)]
        #         use_company_salvager_ids = self.env['tyibs.base.lift.use.company.salvager'].search(
        #             use_company_salvager_domain)
        #         for item in use_company_salvager_ids:
        #             use_company_list.append({
        #                 "company_id": lift_id.use_company_id.id,
        #                 "company_name": item.enterprise_id.name,
        #                 "company_type": u'使用单位',
        #                 "level": dict_roles[item.role],
        #                 "link_man": item.name,
        #                 "link_man_phone": item.mobile,
        #                 "message": u'短信'
        #             })
        #     elif config_item.unit_type == "maintenance":
        #         # 维保单位救援人员
        #         if site_ids:
        #             # 有救援站点
        #             maintenance_company_salvager_domain = [('site_id', 'in', site_ids.ids),
        #                                                ('role', '=', config_item.role)]
        #         else:
        #             maintenance_company_salvager_domain = [('enterprise_id', '=', lift_id.maintenance_company_id.id),
        #                                                ('role', '=', config_item.role)]
        #         maintenance_company_salvager_ids = self.env['tyibs.base.maintenance.company.salvager'].search(
        #             maintenance_company_salvager_domain)
        #         for item in maintenance_company_salvager_ids:
        #             maintenance_company_list.append({
        #                 "company_id": lift_id.maintenance_company_id.id,
        #                 "company_name": item.enterprise_id.name,
        #                 "company_type": u'维保单位',
        #                 "level": dict_roles[item.role],
        #                 "link_man": item.name,
        #                 "link_man_phone": item.mobile,
        #                 "message": u'短信'
        #             })
        # result_list.extend(maintenance_company_list)
        # result_list.extend(use_company_list)
        return maintenance_company_list + use_company_list

    @api.model
    def second_response(self, lift_code):
        """
        二级响应单位,电梯上绑定的救援单位
        :param lift_code: 电梯编码
        :return: 二级救援单位的救援人员资料
        """
        salvager_list = []
        # 救援配置domain：救援、二级、二级救援单位
        er_call_config_domain = [('config_type', '=', 'save'), ('response_level', '=', '2'), ('unit_type', '=', 'salver_company')]
        er_config_ids = self.env['tyibs.er.call.config'].search(er_call_config_domain)
        dict_roles = dict(SALVAGER_ROLES)
        if er_config_ids:
            roles = er_config_ids.mapped("role")
            lift = self.env['tyibs.base.lift'].search([['code', '=', lift_code]])
            if lift:
            # if lift and lift.salvager_unit_id:
                # enterprise_id = lift.salvager_unit_id.id
                # salvager_ids = self.env["tyibs.base.maintenance.company.salvager"].search([
                #     ('enterprise_id','=',enterprise_id),('role','in',roles)])
                # def cmp_role(x,y):
                #     # 自定义排序
                #     role_dict = {
                #         'head_of_unit': 0,
                #         'first_salvager': 1,
                #         'second_salvager': 2,
                #         'third_salvager': 3
                #     }
                #     x = role_dict[x.role]
                #     y = role_dict[y.role]
                #     if x < y:
                #         return -1
                #     elif x > y:
                #         return 1
                #     return 0
                # salvager_ids = sorted(salvager_ids,cmp_role)

                # 2018-7-20 cxd 李辉要求客户端显示所有二级救援单位
                # 按照单位排序
                # 二级救援单位排除自己的维保公司
                salvager_ids = self.env["tyibs.base.maintenance.company.salvager"].search([
                    ('enterprise_id.is_salvager_unit', '=', True),
                    ('enterprise_id', '!=', lift.maintenance_company_id.id), ('role', 'in', roles)])
                def cmp_role(x,y):
                    # 按照单位排序
                    x = x.enterprise_id.id
                    y = y.enterprise_id.id
                    if x < y:
                        return -1
                    elif x > y:
                        return 1
                    return 0
                salvager_ids = sorted(salvager_ids, cmp_role)
                for item in salvager_ids:
                    salvager_list.append({
                        "company_id": item.enterprise_id.id,
                        "company_name": item.enterprise_id.name,
                        "company_type": u'网格救援',
                        "level": dict_roles[item.role],
                        "link_man": item.name,
                        "link_man_phone": item.mobile,
                        "message": u'短信',
                    })
        return salvager_list


    @api.model
    def thread_response(self):
        """
        三级响应：公共救援资源
        :return: 公共救援列表
        """
        return [{
            "company_name": item.name,
            "company_type": u'公共救援',
            "link_man_phone": item.phone
        } for item in self.env['tyibs.er.public'].search([])]


class WorkOrderRepair(models.Model):
    """
    报修
    """
    _inherit = "tyibs.er.work.order.base"
    _name = "tyibs.er.work.order.repair"

    # 跟踪处理的情况
    # comment_ids = fields.One2many("tyibs.er.work.order.compliant.comment", "order_id", string=u"跟踪记录")
    # 基本情况
    content = fields.Text(string=u"报修内容")

    # 归档结束时候添加
    fault_category_id = fields.Many2one(
        "tyibs.base.fault.category", string=u"故障类别")
    fault_item_id = fields.Many2one(
        "tyibs.base.fault.item",
        string=u"故障明细",
        domain="[('category_id','=',fault_category_id)]")
    fault_description = fields.Text(string=u"故障描述")


class WorkOrderCompliant(models.Model):
    """
    投诉
    """
    _inherit = "tyibs.er.work.order.base"
    _name = "tyibs.er.work.order.compliant"

    # 基本情况
    content = fields.Text(string=u"报警内容")


class WorkOrderOperationCategory(models.Model):
    """
    跟踪记录中的活动类型
    """
    _name = "tyibs.er.work.order.operation.category"

    name = fields.Char(string=u"类型名称", size=100, required=True)

    _sql_constraints = [('unique_name', 'unique(name)', '类型名称不能重复')]


class WorkOrderComment(models.Model):
    """
    通用的跟踪日志记录
    """
    _name = "tyibs.er.work.order.comment"
    _rec_name = "contact"
    _order = "do_time desc"
    # 5.9 add code
    arlams_order_num = fields.Char(string=u'所属工单编号')
    # 5.9 add end
    contact = fields.Char(string=u"联系人", size=100, index=True)
    phone = fields.Char(string=u"联系电话", size=50, index=True)
    stage = fields.Selection(
        WORK_ORDER_STATE, string=u"隶属阶段", required=True, default="draft")
    do_time = fields.Datetime(
        string=u"处理时间",
        required=True,
        default=lambda self: fields.Datetime.now())
    # operation_category_id = fields.Many2one("tyibs.er.work.order.operation.category", required=True, string=u"活动类型")
    operation_category_id = fields.Many2one(
        "tyibs.er.work.order.operation.category", string=u"活动类型")
    content = fields.Text(string=u"进展情况")
    operation_content = fields.Text(string=u"活动内容")

    has_record = fields.Boolean(string=u"是否有录音", compute="_compute_has_record", store=True)
    record_attachment_id = fields.Binary(string=u"录音记录", attachment=True, store=True)
    # 如果在后台上传文件这个file_name会自动生成，走接口上传文件的话要指定这个字段，否则就是默认值
    file_name = fields.Char(string=u"文件名", required=True, default=u"录音文件.wma")
    customer_service_id = fields.Many2one(
        "tyibs.base.lift.dispose.center.customer.service", string=u"处理人员")
    called_start_time = fields.Datetime(string=u"通话开始时间")
    called_end_time = fields.Datetime(string=u"通话结束时间")
    time_span = fields.Integer(
        string=u"通话时长(秒)",
        compute="_compute_time_span",
        store=True,
        readonly=True)
    called_type = fields.Selection(
        [("call_in", "呼入"), ("call_out", "呼出")], string=u"呼叫类型")
    action_type = fields.Selection(
        [("ask", "咨询"), ("compliant", "投诉"), ("repair", "报修"), ("save", "救援"),
         ("other", "其它")],
        string=u"工单类型")
    res_model = fields.Char('关联的模型', index=True)
    res_id = fields.Integer('关联的记录', index=True)
    remark = fields.Text(string=u"备注")

    @api.depends("called_start_time", "called_end_time")
    def _compute_time_span(self):
        for item in self:
            if item.called_end_time and item.called_start_time and (
                    item.called_end_time > item.called_start_time):
                start = time.strptime(item.called_start_time,
                                      "%Y-%m-%d %H:%M:%S")
                end = time.strptime(item.called_end_time, "%Y-%m-%d %H:%M:%S")
                item.time_span = int(time.mktime(end) - time.mktime(start))
            else:
                item.time_span = 0

    @api.depends("record_attachment_id")
    def _compute_has_record(self):
        for item in self:
            if item.record_attachment_id:
                item.has_record = True
            else:
                item.has_record = False

    @api.model
    def create(self, vals):
        called_start_time = vals.get("called_start_time", False)
        called_end_time = vals.get("called_end_time", False)
        # 创建的时候去掉郭勇康
        content = vals.get("content", "")
        res_model = vals.get("res_model", False)
        res_id = vals.get("res_id", False)
        if content and u"报警人：郭勇康" in content:
            if res_model and res_id:
                order = self.env[res_model].sudo().search([('id', '=', res_id)])
                if order:
                    content = content.replace(u"报警人：郭勇康", u"报警人：" + order.name)
                    vals["contact"] = order.name
                else:
                    content = content.replace(u"报警人：郭勇康", u"")
            else:
                content = content.replace(u"报警人：郭勇康", u"")
            vals["content"] = content
        if called_start_time and called_end_time and (called_start_time >=
                                                      called_end_time):
            raise Warning(u"通话开始时间必须小于结束时间。")
        return super(WorkOrderComment, self).create(vals)

    def remove_guo_yong_kang(self):
        comment_ids = self.search([('content', 'ilike', u"报警人：郭勇康")])
        for item in comment_ids:
            try:
                if item.res_model and item.res_id:
                    order = self.env[item.res_model].sudo().search([('id', '=', item.res_id)])
                    if order:
                        item.write({
                            'content': item.content.replace(u"报警人：郭勇康", u"报警人：" + order.name),
                            'contact': order.name
                        })
                    else:
                        item.write({
                            'content': item.content.replace(u"报警人：郭勇康", u""),
                        })
                else:
                    item.write({
                        'content': item.content.replace(u"报警人：郭勇康", u""),
                    })
            except Exception, e:
                _logger.info("修改失败,id为{0},错误信息为{1}".format(item.id, e))
        return u"修改完成"


class Lift(models.Model):
    """
    增加一些统计字段, 救援数
    不要实时计算，可以设定时任务
    """
    _inherit = "tyibs.base.lift"

    compliant_count = fields.Integer(string=u"投诉数量")
    repair_count = fields.Integer(string=u"报修数量")
    save_count = fields.Integer(string=u"救援数量")
